<template>
  <div class="chat-list">
    <ChatPreview
      v-for="chat in chatPreviews"
      :key="chat.conversationId"
      :chat="chat"
      @click="openChat(chat.conversationId, chat.userName)"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import userImage from '@/assets/1.svg'
import ChatPreview from '@/component/Chatpreview.vue'
import { wsService } from '../utils/websocket'
import { chatStorage } from '../utils/chatStorage'

// 模拟当前用户ID
const currentUserId = 1

// 添加测试用户数据
const testUsers = {
  1: { name: '我', avatar: userImage },
  2: { name: '快递小哥王', avatar: userImage },
  3: { name: '配送员小李', avatar: userImage },
  4: { name: '客服小张', avatar: userImage },
  5: { name: '取件员小陈', avatar: userImage }
}

// 移除旧的模拟数据
// const conversations = ref([...])
// const messages = ref([...])
// const messageReadStatus = ref([...])

// 处理聊天预览数据
const chatPreviews = ref([])

// 更新预览数据的函数
const updateChatPreviews = () => {
  const conversations = chatStorage.getAllConversations();
  const allMessages = chatStorage.getAllMessages();
  const readStatus = chatStorage.getReadStatus();

  chatPreviews.value = conversations.map(conv => {
    const otherUserId = conv.user1Id === currentUserId ? conv.user2Id : conv.user1Id;
    const conversationMessages = allMessages
      .filter(m => m.conversationId === conv.conversationId)
      .sort((a, b) => new Date(b.sentAt) - new Date(a.sentAt));
    
    const lastMessage = conversationMessages[0];
    
    // 更新未读消息计数逻辑
    const unreadCount = conversationMessages.filter(m => 
      m.senderId !== currentUserId && // 不是自己发送的消息
      !chatStorage.isMessageRead(m.messageId, currentUserId)
    ).length;

    return {
      conversationId: conv.conversationId,
      userName: testUsers[otherUserId].name,
      avatar: testUsers[otherUserId].avatar,
      lastMessage: lastMessage?.content || '',
      lastMessageTime: lastMessage?.sentAt || conv.startedAt,
      unreadCount
    };
  });
}

const router = useRouter()

const openChat = (conversationId, userName) => {
  router.push({ 
    name: 'ChatWindow', 
    params: { id: conversationId }, // 仅传递 conversationId
    query: { userName } // 将 userName 作为查询参数传递
  });
}

// 修改测试消息发送函数
const addTestMessage = (conversationId, content) => {
  const message = {
    messageId: Date.now(),
    conversationId,
    senderId: 2, // 模拟对方发送
    content,
    sentAt: new Date().toISOString()
  };
  
  // 使用 chatStorage 来添加消息
  chatStorage.addMessage(message);
  // 更新预览
  updateChatPreviews();
}

onMounted(() => {
  // 初始化 WebSocket 连接
  wsService.connect(currentUserId)
  
  // 获取初始会话列表
  updateChatPreviews()
  
  // 监听新消息以更新预览
  wsService.onMessage((message) => {
    if (message.type === 'chat_message') {
      // 收到新消息时更新整个预览列表
      updateChatPreviews();
    }
  });
});
</script>

<style scoped>
.chat-list {
  padding: 1rem 0;
  background: #ffffff;
  height: 100%;
  overflow-y: auto;
}
</style>